package com.spring;

import com.tanjiaming99.service.MyBeanPostProcessor;

import java.io.File;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.nio.file.FileStore;
import java.time.temporal.JulianFields;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author tanjiaming99.com
 * @Date 2021/12/14 21:19
 **/
public class ApplicationContext {

    private Class configClass;
    /**
     * 存的单例对象
     */
    private Map<String, Object> singletonObjects = new ConcurrentHashMap<>();
    /**
     * 存所有bean的定义
     */
    private Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>();

    private List<BeanPostProcessor> beanPostProcessorList = new ArrayList<>();

    public ApplicationContext(Class configClass) {
        this.configClass = configClass;

        scan(configClass);

        // 创建单例bean
        for (String beanName : beanDefinitionMap.keySet()) {
            BeanDefinition beanDefinition = beanDefinitionMap.get(beanName);
            if (beanDefinition.getScope().equals("singleton")) {
                Object bean = createBean(beanName, beanDefinition);
                singletonObjects.put(beanName, bean);
            }
        }

    }

    /**
     * 创建bean对象
     *
     * @param beanDefinition
     * @return
     */
    public Object createBean(String beanName, BeanDefinition beanDefinition) {
        Class clazz = beanDefinition.getClazz();
        try {
            Object instance = clazz.getDeclaredConstructor().newInstance();
            // 简单的DI
            // 对属性进行赋值，即依赖注入
            for (Field declaredField : clazz.getDeclaredFields()) {
                if (declaredField.isAnnotationPresent(Autowired.class)) {




                    // 加了@Autowired才会为它赋值

                    // byName byType
                    // 因为这里只能拿到类型或者名字信息
                    // 直接根据属性的名字找
                    // TODO: byName byType 循环依赖
                    Object bean = getBean(declaredField.getName());
                    Autowired autowired = declaredField.getDeclaredAnnotation(Autowired.class);
                    if (Objects.isNull(bean) && autowired.require()) {
                        throw new NullPointerException("required=true，但所需对象不能为空");
                    }
                    // 爆破权限
                    declaredField.setAccessible(true);
                    declaredField.set(instance, bean);
                }
            }
            // Aware
            // 是否实现了这个BeanNameAware接口
            if (instance instanceof BeanNameAware) {
                // spring做这个注入名字的方法
                ((BeanNameAware) instance).setBeanName(beanName);
            }
            // 前
            for (BeanPostProcessor beanPostProcessor : beanPostProcessorList) {
                instance = beanPostProcessor.postProcessBeforeInitialization(instance, beanName);
            }

            // 初始化
            if (instance instanceof InitializingBean) {
                ((InitializingBean) instance).afterPropertiesSet();
            }
            // 后
            for (BeanPostProcessor beanPostProcessor : beanPostProcessorList) {
                instance = beanPostProcessor.postProcessAfterInitialization(instance, beanName);
            }

            // BeanPostProcessor
            return instance;
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * ComponentScan注解可以解析---》扫描路径---》扫描--》BeanDefinition-->BeanDefinitionMap
     *
     * @param configClass
     */
    private void scan(Class configClass) {
        if (!configClass.isAnnotationPresent(ComponentScan.class)) {
            System.out.println("不是配置类。");
            return;
        }
        // 解析配置类
        // 拿到注解
        ComponentScan componentScan = (ComponentScan) configClass.getDeclaredAnnotation(ComponentScan.class);
        // 扫描路径
        String path = componentScan.value();
//        System.out.println(path);

        // 扫描，怎么拿到这个路径下的包呢？
        // 拿到应用类加载器
        ClassLoader classLoader = ApplicationContext.class.getClassLoader();
        URL resource = classLoader.getResource(path.replace(".", "/"));
        File file = new File(resource.getFile());
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (File f : files) {
                String className = f.getAbsolutePath();
                // 不是.class不处理
                if (!className.endsWith(".class")) {
                    continue;
                }
                // 截取类名，注意是左闭右开的
                int front = className.lastIndexOf("\\");
                int end = className.lastIndexOf(".class");
                className = path + "." + className.substring(front + 1, end);
//                System.out.println(className);
                try {
                    Class<?> clazz = classLoader.loadClass(className);
                    if (clazz.isAnnotationPresent(Component.class)) {
                        // 是否实现这个接口
                        if (BeanPostProcessor.class.isAssignableFrom(clazz)) {
                            BeanPostProcessor beanPostProcessor = (BeanPostProcessor) clazz.getDeclaredConstructor().newInstance();
                            beanPostProcessorList.add(beanPostProcessor);
                        }
                        // 表示当前的类是bean，
                        // 解析类，判断当前bean是单例的还是原型的
                        // 所以需要一个bean definition
                        Component component = clazz.getDeclaredAnnotation(Component.class);
                        String beanName = component.value();
                        BeanDefinition beanDefinition = new BeanDefinition();
                        beanDefinition.setClazz(clazz);
                        // 看看它有没有设置scope
                        if (clazz.isAnnotationPresent(Scope.class)) {
                            Scope scope = clazz.getDeclaredAnnotation(Scope.class);
                            beanDefinition.setScope(scope.value());
                        } else {
                            // 没有的话，就是单例
                            beanDefinition.setScope("singleton");
                        }
                        // 全部的bean都丢到里面
                        beanDefinitionMap.put(beanName, beanDefinition);


                    }
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                } catch (InstantiationException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }

            }
        }
    }

    public Object getBean(String beanName) {
        if (beanDefinitionMap.containsKey(beanName)) {
            BeanDefinition beanDefinition = beanDefinitionMap.get(beanName);
            if (beanDefinition.getScope().equals("singleton")) {
                // 确保是单例bean
                return singletonObjects.get(beanName);
            } else {
                // 多例的，创建一个新的bean对象
                return createBean(beanName, beanDefinition);
            }
        } else {
            throw new NullPointerException("不存在对应的bean");
        }
    }
}
